<template>
  <div class="student-detail-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ name: 'student-id' }">学生账号管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生详情</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>学生详情信息</span>
          <el-button v-if="!isEditMode" type="primary" @click="handleEdit">
            <el-icon>
              <Edit />
            </el-icon>
            编辑
          </el-button>
        </div>
      </template>

      <div v-loading="loading" class="detail-content">
        <!-- 查看模式 -->
        <el-descriptions v-if="!isEditMode" :column="2" border>
          <el-descriptions-item label="学号">{{ studentDetail.studentNum || '-' }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ studentDetail.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ studentDetail.gender === 1 ? '男' : (studentDetail.gender === 0 ? '女' : '-') }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">{{ studentDetail.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="学院">{{ studentDetail.grade || '-' }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ studentDetail.className || '-' }}</el-descriptions-item>
          <el-descriptions-item label="GPA">
            {{ studentDetail.gpa !== undefined && studentDetail.gpa !== null ? studentDetail.gpa.toFixed(2) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="studentDetail.status === 1 ? 'success' : 'danger'" size="small">
              {{ studentDetail.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="违纪记录">
            {{ studentDetail.indiscipline === 0 ? '无' : '有' }}
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ studentDetail.idNumber || '-' }}</el-descriptions-item>
          <el-descriptions-item label="紧急联系人">{{ studentDetail.emeContact || '-' }}</el-descriptions-item>
          <el-descriptions-item label="紧急联系人电话">{{ studentDetail.emePhone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="家庭住址" :span="2">{{ studentDetail.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="爱好" :span="2">{{ studentDetail.hobby || '-' }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">{{ studentDetail.problemMsg || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ studentDetail.createTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ studentDetail.updateTime || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 编辑模式 -->
        <el-form v-else ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="120px"
          class="edit-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学号" prop="studentNum">
                <el-input v-model="editForm.studentNum" placeholder="请输入学号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="editForm.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="editForm.gender">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="0">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="editForm.phone" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学院" prop="grade">
                <el-input v-model="editForm.grade" placeholder="请输入学院" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班级" prop="className">
                <el-input v-model="editForm.className" placeholder="请输入班级" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="GPA" prop="gpa">
                <el-input-number v-model="editForm.gpa" :min="0" :max="4.0" :step="0.1" :precision="2"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="editForm.status">
                  <el-radio :label="1">正常</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="违纪记录" prop="indiscipline">
                <el-radio-group v-model="editForm.indiscipline">
                  <el-radio :label="0">无</el-radio>
                  <el-radio :label="1">有</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idNumber">
                <el-input v-model="editForm.idNumber" placeholder="请输入身份证号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="紧急联系人" prop="emeContact">
                <el-input v-model="editForm.emeContact" placeholder="请输入紧急联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系人电话" prop="emePhone">
                <el-input v-model="editForm.emePhone" placeholder="请输入紧急联系人电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="editForm.address" type="textarea" :rows="2" placeholder="请输入家庭住址" />
          </el-form-item>

          <el-form-item label="爱好" prop="hobby">
            <el-input v-model="editForm.hobby" type="textarea" :rows="2" placeholder="请输入爱好" />
          </el-form-item>

          <el-form-item label="问题描述" prop="problemMsg">
            <el-input v-model="editForm.problemMsg" type="textarea" :rows="3" placeholder="请输入问题描述" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              提交修改
            </el-button>
            <el-button @click="handleReset">复原</el-button>
            <el-button @click="handleCancel">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { getStudentById, updateStudent, type CreateStudentRequest } from '../../api/studentInfo'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const isEditMode = ref(false)
const submitting = ref(false)
const editFormRef = ref<FormInstance>()

// 保存原始数据用于复原
const originalData = ref<any>(null)

// 学生详情数据
const studentDetail = ref({
  id: 0,
  userId: 0,
  studentNum: '',
  name: '',
  gender: 0,
  phone: '',
  className: '',
  grade: '',
  gpa: 0,
  counselorId: 0,
  avatarUrl: null as string | null,
  idNumber: null as string | null,
  hobby: null as string | null,
  emeContact: null as string | null,
  emePhone: null as string | null,
  address: null as string | null,
  problemMsg: '',
  email: '',
  indiscipline: 0,
  nameCheckStatus: 0,
  studentNumCheckStatus: 0,
  classCheckStatus: 0,
  phoneCheckStatus: 0,
  status: 1,
  createTime: '',
  updateTime: null as string | null,
  createBy: 0,
  updateBy: null as number | null
})

// 获取学生详情
const fetchStudentDetail = async () => {
  const studentId = route.params.id
  if (!studentId) {
    ElMessage.error('学生ID不存在')
    router.push({ name: 'student-id' })
    return
  }

  // 处理路由参数，可能是 string 或 string[]
  const idStr = Array.isArray(studentId) ? studentId[0] : studentId
  const id = typeof idStr === 'string' ? parseInt(idStr) : (typeof idStr === 'number' ? idStr : 0)

  if (!id || isNaN(id)) {
    ElMessage.error('学生ID格式错误')
    router.push({ name: 'student-id' })
    return
  }

  // 优先从 sessionStorage 读取列表接口返回的数据
  try {
    const storedData = sessionStorage.getItem('currentStudentDetail')
    if (storedData) {
      const data = JSON.parse(storedData)
      // 验证ID是否匹配
      const storedId = typeof data.id === 'number' ? data.id : (typeof data.id === 'string' ? parseInt(data.id) || 0 : 0)
      if (storedId === id) {
        // 使用列表接口返回的数据
        loadStudentDetailFromData(data)
        // 清除 sessionStorage 中的数据
        sessionStorage.removeItem('currentStudentDetail')
        return
      }
    }
  } catch (error) {
    console.warn('读取 sessionStorage 数据失败:', error)
  }

  // 如果没有 sessionStorage 数据，则调用详情接口
  loading.value = true
  try {
    const response = await getStudentById(id)

    if (response.code === '200' && response.data) {
      loadStudentDetailFromData(response.data)
    } else {
      ElMessage.error(response.msg || '获取学生详情失败')
      router.push({ name: 'student-id' })
    }
  } catch (error) {
    console.error('获取学生详情失败:', error)
    ElMessage.error('获取学生详情失败，请稍后重试')
    router.push({ name: 'student-id' })
  } finally {
    loading.value = false
  }
}

// 编辑表单数据
const editForm = reactive({
  id: 0,
  userId: 0,
  studentNum: '',
  name: '',
  gender: 0,
  phone: '',
  className: '',
  grade: '',
  gpa: 0,
  counselorId: 0,
  idNumber: '',
  hobby: '',
  emeContact: '',
  emePhone: '',
  address: '',
  problemMsg: '',
  email: '',
  indiscipline: 0,
  nameCheckStatus: 0,
  studentNumCheckStatus: 0,
  classCheckStatus: 0,
  phoneCheckStatus: 0,
  status: 1,
  createTime: '',
  updateTime: '',
  createBy: 0,
  updateBy: 0
})

// 表单验证规则
const editFormRules: FormRules = {
  studentNum: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请输入学院', trigger: 'blur' }
  ],
  className: [
    { required: true, message: '请输入班级', trigger: 'blur' }
  ],
  gpa: [
    { type: 'number', min: 0, max: 4.0, message: 'GPA必须在0-4.0之间', trigger: 'blur' }
  ]
}

// 从数据对象加载学生详情
const loadStudentDetailFromData = (data: any) => {
  // 保存原始数据
  originalData.value = JSON.parse(JSON.stringify(data))

  // 格式化创建时间
  let createTimeStr = ''
  if (data.createTime) {
    try {
      const date = new Date(data.createTime)
      createTimeStr = date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    } catch (e) {
      createTimeStr = data.createTime
    }
  }

  studentDetail.value = {
    id: typeof data.id === 'number' ? data.id : (typeof data.id === 'string' ? parseInt(data.id) || 0 : 0),
    userId: data.userId || 0,
    studentNum: data.studentNum || '',
    name: data.name || '',
    gender: data.gender !== undefined ? data.gender : 0,
    phone: data.phone || '',
    className: data.className || '',
    grade: data.grade || '',
    gpa: data.gpa !== undefined ? data.gpa : 0,
    counselorId: data.counselorId || 0,
    avatarUrl: data.avatarUrl || null,
    idNumber: data.idNumber || null,
    hobby: data.hobby || null,
    emeContact: data.emeContact || null,
    emePhone: data.emePhone || null,
    address: data.address || null,
    problemMsg: data.problemMsg || '',
    email: data.email || '',
    indiscipline: data.indiscipline !== undefined ? data.indiscipline : 0,
    nameCheckStatus: data.nameCheckStatus !== undefined ? data.nameCheckStatus : 0,
    studentNumCheckStatus: data.studentNumCheckStatus !== undefined ? data.studentNumCheckStatus : 0,
    classCheckStatus: data.classCheckStatus !== undefined ? data.classCheckStatus : 0,
    phoneCheckStatus: data.phoneCheckStatus !== undefined ? data.phoneCheckStatus : 0,
    status: data.status !== undefined ? data.status : 1,
    createTime: createTimeStr,
    updateTime: data.updateTime || null,
    createBy: data.createBy || 0,
    updateBy: data.updateBy || null
  }
}

// 进入编辑模式
const handleEdit = () => {
  // 禁用状态账号不可进入编辑模式
  const disabled = Number(studentDetail.value.status) === 0
  if (disabled) {
    ElMessage.warning('该账号已禁用，无法编辑')
    return
  }
  isEditMode.value = true
  // 将学生详情数据复制到编辑表单
  editForm.id = studentDetail.value.id
  editForm.userId = studentDetail.value.userId
  editForm.studentNum = studentDetail.value.studentNum
  editForm.name = studentDetail.value.name
  editForm.gender = studentDetail.value.gender
  editForm.phone = studentDetail.value.phone
  editForm.className = studentDetail.value.className
  editForm.grade = studentDetail.value.grade
  editForm.gpa = studentDetail.value.gpa
  editForm.counselorId = studentDetail.value.counselorId
  editForm.idNumber = studentDetail.value.idNumber || ''
  editForm.hobby = studentDetail.value.hobby || ''
  editForm.emeContact = studentDetail.value.emeContact || ''
  editForm.emePhone = studentDetail.value.emePhone || ''
  editForm.address = studentDetail.value.address || ''
  editForm.problemMsg = studentDetail.value.problemMsg
  editForm.email = studentDetail.value.email || ''
  editForm.indiscipline = studentDetail.value.indiscipline
  editForm.nameCheckStatus = studentDetail.value.nameCheckStatus
  editForm.studentNumCheckStatus = studentDetail.value.studentNumCheckStatus
  editForm.classCheckStatus = studentDetail.value.classCheckStatus
  editForm.phoneCheckStatus = studentDetail.value.phoneCheckStatus
  editForm.status = studentDetail.value.status
  editForm.createTime = originalData.value?.createTime || ''
  editForm.updateTime = originalData.value?.updateTime || ''
  editForm.createBy = studentDetail.value.createBy
  editForm.updateBy = studentDetail.value.updateBy || 0
}

// 提交修改
const handleSubmit = async () => {
  if (!editFormRef.value) return
  // 再次防护：禁用状态不可提交修改
  if (Number(editForm.status) === 0) {
    ElMessage.error('禁用账号不可编辑')
    return
  }

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 构建更新请求数据
        const updateData: CreateStudentRequest = {
          id: editForm.id,
          userId: editForm.userId,
          name: editForm.name,
          studentNum: editForm.studentNum,
          grade: editForm.grade,
          className: editForm.className,
          phone: editForm.phone,
          problemMsg: editForm.problemMsg,
          email: editForm.email || '',
          gpa: editForm.gpa,
          indiscipline: editForm.indiscipline,
          nameCheckStatus: editForm.nameCheckStatus,
          studentNumCheckStatus: editForm.studentNumCheckStatus,
          classCheckStatus: editForm.classCheckStatus,
          phoneCheckStatus: editForm.phoneCheckStatus,
          status: editForm.status,
          createTime: editForm.createTime,
          updateTime: editForm.updateTime || '',
          createBy: editForm.createBy,
          updateBy: editForm.updateBy
        }

        // console.log('updateData:', updateData)
        const response = await updateStudent(updateData)

        if (response.code === '200') {
          ElMessage.success('修改成功')
          // 重新加载数据
          const res = await getStudentById(editForm.userId)
          console.log('新的res:', res)
          // await fetchStudentDetail()
          isEditMode.value = false
        } else {
          ElMessage.error(response.msg || '修改失败')
        }
      } catch (error) {
        console.error('提交修改失败:', error)
        ElMessage.error('提交修改失败，请稍后重试')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 复原
const handleReset = () => {
  if (originalData.value) {
    // 重新加载原始数据
    loadStudentDetailFromData(originalData.value)
    // 重新填充编辑表单
    handleEdit()
  }
}

// 返回（退出编辑模式）
const handleCancel = () => {
  isEditMode.value = false
  editFormRef.value?.resetFields()
}

onMounted(() => {
  fetchStudentDetail()
})
</script>

<style scoped>
.student-detail-container {
  padding: 0;
}

.breadcrumb {
  margin-bottom: 20px;
}

.detail-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
}

.detail-content {
  padding: 20px 0;
}

.edit-form {
  padding: 20px 0;
}
</style>
